package com.itheima.bos.service.impl;

import com.itheima.bos.dao.IRoleDao;
import com.itheima.bos.dao.IUserDao;
import com.itheima.bos.domain.Role;
import com.itheima.bos.domain.User;
import com.itheima.bos.service.IUserService;
import com.itheima.bos.utils.MD5Utils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Mr.King on 2017/3/7.
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao dao;

    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private ProcessEngine processEngine;

    /*public User login(User model){
        String password = MD5Utils.md5(model.getPassword());
        List list = dao.findNameQuery("login", model.getUsername(), password);
        if (list != null && list.size() > 0){
            return (User) list.get(0);
        }
        return null;
    }*/

    @Override
    public void editPassword(String password, String id) {
        password = MD5Utils.md5(password);
        dao.executeNameQuery("editPassword",password,id);
    }

    @Override
    public void save(User model,String[] roleIds) {
        String password = MD5Utils.md5(model.getPassword());
        model.setPassword(password);
        dao.save(model);

        //创建保存用户
        org.activiti.engine.identity.User user = new UserEntity();
        user.setId(model.getId());
        processEngine.getIdentityService().saveUser(user);

        if (roleIds != null && roleIds.length>0){
            for (String id : roleIds){
//                Role role = new Role(id);
                Role role = roleDao.findById(id);
                model.getRoles().add(role);

                //把用户添加到组
                processEngine.getIdentityService().createMembership(user.getId(),role.getName());
            }
        }
    }

    @Override
    public List<User> findAll() {
        return dao.findAll();
    }
}
